import BaseUI from "./BaseUI";

class ItemInfo {
    id: number = 0;
    itemNode: cc.Node;
}

/**
 * ScrollView组件选择滚动方向
 */
enum SCROLLVIEW_DIRECTION {
    NONE = 0,
    VERTICAL = 1,
    HPRIZONTAL = 2
}
/**
 * 根据ScrollView组件选择决定Content节点垂直排列
 */
enum CONTENT_DIRECTION_VERTICAL {
    TOP_TO_BOTTON = 11,
    BOTTON_TO_TOP = 22
}
/**
 * 根据ScrollView组件选择决定Content节点水平排列
 */
enum CONTENT_DIRECTION_HORIZONTAL {
    LEFT_TO_RIGHT = 33,
    RIGHT_TO_LEFT = 44
}

/**
 * 选择一个自动移动的方向竖向
 */
enum AUTO_DIRECTION_VERTICAL {
    TO_TOP = 111,
    TO_BOTTON = 222
}
/**
 *  选择一个自动移动的方向横向
 */
enum AUTO_DIRECTION_HORIZONTAL {
    TO_LEFT = 333,
    TO_RIGHT = 444
}

const { ccclass, property, executionOrder } = cc._decorator;
const offsetCount: number = 5;
const nameStr: string = 'itemNode_';
@ccclass
@executionOrder(-100) //保证优先级
export default class LoopScroll extends cc.Component {

    @property({ type: cc.Slider, tooltip: 'Slider节点：默认可为null', })
    slider: cc.Slider = null;

    @property({ type: cc.Node, tooltip: 'itemNode节点', })
    itemNode: cc.Node = null;

    @property({
        tooltip: 'itemNode节点排列之间的间隔值',
    })
    spacing: number = 0;


    @property({
        type: cc.Enum(CONTENT_DIRECTION_VERTICAL),
        visible() {
            let scrollView: cc.ScrollView = this._getComponent(this.node, cc.ScrollView) as cc.ScrollView;
            return scrollView.vertical;
        },
        tooltip: 'TOP_TO_BOTTON代表：排列方式从上到下\n   BOTTON_TO_TOP代表：排列方式从下到上',
    })
    contentDirectionVertical: CONTENT_DIRECTION_VERTICAL = CONTENT_DIRECTION_VERTICAL.TOP_TO_BOTTON;

    @property({
        type: cc.Enum(CONTENT_DIRECTION_HORIZONTAL),
        visible() {
            let scrollView: cc.ScrollView = this._getComponent(this.node, cc.ScrollView) as cc.ScrollView;
            return scrollView.horizontal;
        },
        tooltip: 'LEFT_TO_RIGHT代表：排列方式从左到右\n   RIGHT_TO_LEFT代表：排列方式从右到左',
    })
    contentDirectionHorizontal: CONTENT_DIRECTION_HORIZONTAL = CONTENT_DIRECTION_HORIZONTAL.RIGHT_TO_LEFT;


    //+++++++++++++++++自动模式
    @property({ tooltip: '勾选开启自动模式，否则为手动模式', })
    isOpenAuto: boolean = false;

    @property({
        tooltip: '自动移动速度',
        min: 0,
        visible() {
            return this.isOpenAuto;
        }
    })
    autoSpeed: number = 10;

    @property({
        type: cc.Enum(AUTO_DIRECTION_VERTICAL),
        visible() {
            let scrollView: cc.ScrollView = this._getComponent(this.node, cc.ScrollView) as cc.ScrollView;
            return scrollView.vertical && this.isOpenAuto;
        },
        tooltip: 'TO_TOP代表：向上自动移动\n   TO_BOTTON代表：向下自动移动',
    })
    autoDirectionVertical: AUTO_DIRECTION_VERTICAL = AUTO_DIRECTION_VERTICAL.TO_TOP;

    @property({
        type: cc.Enum(AUTO_DIRECTION_HORIZONTAL),
        visible() {
            let scrollView: cc.ScrollView = this._getComponent(this.node, cc.ScrollView) as cc.ScrollView;
            return scrollView.horizontal && this.isOpenAuto;
        },
        tooltip: 'TO_LEFT代表：向左自动移动\n   TO_BOTTON代表：向右自动移动',
    })
    autoDirectionHorizontal: AUTO_DIRECTION_HORIZONTAL = AUTO_DIRECTION_HORIZONTAL.TO_RIGHT;


    //-通用部分
    private m_ItemInfos: ItemInfo[] = [];
    private m_Delegate: BaseUI = null;
    private m_View: cc.Node = null;
    private m_Content: cc.Node = null;
    private m_Widget: cc.Widget = null;
    private m_ScrollView: cc.ScrollView = null;
    private m_ScrollViewDirection: SCROLLVIEW_DIRECTION = SCROLLVIEW_DIRECTION.NONE;        // 代表scrollView选择的方向
    private m_ContentDirection: CONTENT_DIRECTION_VERTICAL | CONTENT_DIRECTION_HORIZONTAL;  // 代表content选择排列的方向

    //-手动部分
    private m_FlagDir: number = 0;
    private m_OffsetHW: number = 0;           // 偏差值
    private m_ShowCount: number = 0;          // view尺寸下能展示的节点数
    private m_Boundary1: number = 0;          // 右||上边界，到达后可进行刷新
    private m_Boundary2: number = 0;          // 左||下边界，到达后可进行刷新
    private m_LastContentPos: cc.Vec3 = null; // 代表上一次content的位置
    private m_ContentAnchorMap: Map<CONTENT_DIRECTION_VERTICAL | CONTENT_DIRECTION_HORIZONTAL, cc.Vec2> = new Map();    // 预存储content节点锚点，用于不同状态下位置的控制
    private m_WidgetFuntionMAP: Map<CONTENT_DIRECTION_VERTICAL | CONTENT_DIRECTION_HORIZONTAL, () => void> = new Map(); // 预存储widget组件设置函数,用于不同状态下位置的控制
    private m_DirectionFlagMap: Map<CONTENT_DIRECTION_VERTICAL | CONTENT_DIRECTION_HORIZONTAL, number> = new Map();     // 预存储方向标志1,-1，用于滑动过程中不同方向的系数值

    //-自动部分
    private m_isMoveState: boolean = false;
    private m_AutoDirection: AUTO_DIRECTION_VERTICAL | AUTO_DIRECTION_HORIZONTAL;  // 代表content选择排列的方向
    private m_MaxShowCount: number = 0;
    private m_SumNodeCount: number = 0;
    private m_LoopDataCount: number = 0;
    private m_LoopNodeCount: number = 0;

    //-slider部分
    private m_SliderLength: number = 0;         //记录可滑动距离
    private m_InTouchSlider: boolean = false;   //
    private m_CountInitPiont: cc.Vec3 = null;   //countent的原始位置


    onLoad() {
        this.m_View = cc.find('view', this.node);
        this.m_Content = cc.find('view/content', this.node);
        this.m_ScrollView = this._getComponent(this.node, cc.ScrollView) as cc.ScrollView;
        this.m_Widget = this._getComponent(cc.find('view/content', this.node), cc.Widget) as cc.Widget;
    }

    start() {
        this._initMapData();
        this.m_ScrollViewDirection = this._getDirectionFromScrollView();
        if (this.m_ScrollViewDirection != SCROLLVIEW_DIRECTION.NONE) {
            this.m_ContentDirection = this._getDirectionFromContent();
            this._initScrollView();
            this._initCommonData();
        }
    }

    /**
     * @param tempNode node节点
     * @param tempName node节点组件
     * @returns 
     */
    private _getComponent(tempNode: cc.Node, tempName: typeof cc.Component): cc.Component {
        if (!tempNode || !tempName) { return; }
        let component: cc.Component = tempNode.getComponent(tempName);
        if (component) {
            return component;
        }
        else {
            return tempNode.addComponent(tempName);
        }
    }

    /**
     * initMapData容器数据包括：contentm锚点/位置/方向标识
     * 使用widget组件控制位置，避免调整锚点出现位置的偏差问题
     */
    private _initMapData(): void {
        let topfun: () => void = () => {
            this.m_Widget.isAlignTop = true;
            this.m_Widget.top = 0;
        }
        let bottonFun: () => void = () => {
            this.m_Widget.isAlignBottom = true;
            this.m_Widget.bottom = 0;
        }
        let leftFun: () => void = () => {
            this.m_Widget.isAlignLeft = true;
            this.m_Widget.left = 0;
        }
        let rightFun: () => void = () => {
            this.m_Widget.isAlignRight = true;
            this.m_Widget.right = 0;
        }

        this.m_ContentAnchorMap.set(CONTENT_DIRECTION_VERTICAL.TOP_TO_BOTTON, cc.v2(0.5, 1));
        this.m_ContentAnchorMap.set(CONTENT_DIRECTION_VERTICAL.BOTTON_TO_TOP, cc.v2(0.5, 0));
        this.m_ContentAnchorMap.set(CONTENT_DIRECTION_HORIZONTAL.LEFT_TO_RIGHT, cc.v2(0, 0.5));
        this.m_ContentAnchorMap.set(CONTENT_DIRECTION_HORIZONTAL.RIGHT_TO_LEFT, cc.v2(1, 0.5));

        this.m_WidgetFuntionMAP.set(CONTENT_DIRECTION_VERTICAL.TOP_TO_BOTTON, topfun);
        this.m_WidgetFuntionMAP.set(CONTENT_DIRECTION_VERTICAL.BOTTON_TO_TOP, bottonFun);
        this.m_WidgetFuntionMAP.set(CONTENT_DIRECTION_HORIZONTAL.LEFT_TO_RIGHT, leftFun);
        this.m_WidgetFuntionMAP.set(CONTENT_DIRECTION_HORIZONTAL.RIGHT_TO_LEFT, rightFun);

        this.m_DirectionFlagMap.set(CONTENT_DIRECTION_VERTICAL.TOP_TO_BOTTON, 1);
        this.m_DirectionFlagMap.set(CONTENT_DIRECTION_VERTICAL.BOTTON_TO_TOP, -1);
        this.m_DirectionFlagMap.set(CONTENT_DIRECTION_HORIZONTAL.LEFT_TO_RIGHT, -1);
        this.m_DirectionFlagMap.set(CONTENT_DIRECTION_HORIZONTAL.RIGHT_TO_LEFT, 1);

        //自动模式下关闭scrollView交互
        this.m_ScrollView.enabled = this.isOpenAuto == true ? false : true;
    }
    /**
     * initScrollView初始布局
     */
    private _initScrollView(): void {
        this.m_ScrollView.node.setAnchorPoint(0.5, 0.5);
        this.m_View.setAnchorPoint(0.5, 0.5);
        this.m_Content.setAnchorPoint(0.5, 0.5);
        this.m_View.position = this.m_Content.position = cc.Vec3.ZERO;

        //设置content的位置和锚点
        let anchor: cc.Vec2 = this.m_ContentAnchorMap.get(this.m_ContentDirection);
        this.m_Content.setAnchorPoint(anchor);
        this.m_WidgetFuntionMAP.get(this.m_ContentDirection)();
        this.m_Widget.updateAlignment();
    }
    /**
     * 部分变量赋值
     */
    private _initCommonData(): void {
        [this.m_Boundary1, this.m_Boundary2] = this._getBoundaryFromDirecton();
        this.m_ShowCount = this._getShowCountsFromView();
        this.m_ItemInfos = this._getContentChildren();
        this.m_OffsetHW = this._getOffsetHWFromDirection();
        this.m_LastContentPos = this.m_Content.position;

        if (this.isOpenAuto) {
            //自动
            this.m_AutoDirection = this._getDirectionFromAuto();
        }
        else {
            //手动
            this.m_FlagDir = this.m_DirectionFlagMap.get(this.m_ContentDirection);
            //slider
            this._initSlider();
        }
    }
    /**
     * 获取scrollView选择的方向
     * @returns
     */
    private _getDirectionFromScrollView(): SCROLLVIEW_DIRECTION {
        if (this.m_ScrollView.vertical && !this.m_ScrollView.horizontal) {
            return SCROLLVIEW_DIRECTION.VERTICAL;
        }
        else if (!this.m_ScrollView.vertical && this.m_ScrollView.horizontal) {
            return SCROLLVIEW_DIRECTION.HPRIZONTAL;
        }

        console.warn('检查ScrollView组件并勾选一个方向');
        return SCROLLVIEW_DIRECTION.NONE;
    }
    /**
     * content的选择排列方式
     * @returns 
     */
    private _getDirectionFromContent(): CONTENT_DIRECTION_VERTICAL | CONTENT_DIRECTION_HORIZONTAL {
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.VERTICAL) {
            return this.contentDirectionVertical;
        }
        else if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.HPRIZONTAL) {
            return this.contentDirectionHorizontal;
        }
    }





    //+++++++++++++++++++++++++++++++++++++++++手动模式
    //+++++++++++++++++++++++++++++++++++++++++手动模式
    /**
     * 按照scrollView选择的方向确定view尺寸下能展示出ItemNode的个数
     * @returns  展示的个数
     */
    private _getShowCountsFromView(): number {
        if (!this.itemNode) {
            cc.warn('itemNode属性值不能为null');
            return;
        }

        let showCount: number = 0;
        let allWidth: number = this.m_View.width;
        let allHeight: number = this.m_View.height;
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.HPRIZONTAL) {
            let singleValue: number = this.itemNode.width + this.spacing;
            if (allWidth <= 0 || singleValue <= 0) {
                cc.warn('View节点width不能为0 || boundary属性设置大于View节点width || itemNode.width属性设置不能是0')
            }
            else {
                try {
                    showCount = Math.ceil(allWidth / singleValue);
                } catch (error) {
                    console.warn(error.message);
                    console.warn(error.stack.toString());
                }
            }
        }
        else if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.VERTICAL) {
            let singleValue: number = this.itemNode.height + this.spacing;
            if (allHeight <= 0 || singleValue <= 0) {
                cc.warn('View节点height不能为0 || boundary属性设置大于View节点height || itemNode.heigth属性设置不能是0')
            }
            else {
                try {
                    showCount = Math.ceil(allHeight / singleValue);
                } catch (error) {
                    console.warn(error.message);
                    console.warn(error.stack.toString());
                }
            }
        }

        return showCount + offsetCount; //+2的目的是防止刷新过程中存在的延迟情况
    }
    /**
     * 获取content下的孩子个数，如果无孩子个数则进行动态生成
     * @returns 
     */
    private _getContentChildren(): ItemInfo[] {
        let tempArray: ItemInfo[] = [];
        this.m_Content.children.forEach((value: cc.Node, index: number) => {
            let itemInfo: ItemInfo = new ItemInfo();
            itemInfo.id = index;
            itemInfo.itemNode = value;
            itemInfo.itemNode.active = false;
            tempArray.push(itemInfo);
        })

        //动态生成，这里我们生成需要展示的个数。
        if (tempArray.length == 0) {
            for (let i = 0; i < this.m_ShowCount; i++) {
                let itemNode: cc.Node = cc.instantiate(this.itemNode);
                itemNode.parent = this.m_Content;
                itemNode.active = false;
                itemNode.position = this._getPosFromDirction(i);

                let itemInfo: ItemInfo = new ItemInfo();
                itemInfo.id = i;
                itemInfo.itemNode = itemNode;
                tempArray.push(itemInfo);
            }
        }

        return tempArray;
    }
    /**
     * 获取更换位置的偏差值
     * @returns 
     */
    private _getOffsetHWFromDirection(): number {
        if (!this.itemNode) {
            cc.warn('itemNode属性值不能为null');
            return;
        }

        let _width: number = this.itemNode.width;
        let _height: number = this.itemNode.height;
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.VERTICAL) {
            return (_height + this.spacing) * this.m_ItemInfos.length;
        }
        else if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.HPRIZONTAL) {
            return (_width + this.spacing) * this.m_ItemInfos.length;
        }
    }
    /**
     * 定义两个边界当超越边界后进行位置更换即刷新（同时防止刷新存在肉眼可见的延迟情况）
     * @returns 
     */
    private _getBoundaryFromDirecton(): number[] {
        if (!this.itemNode) {
            cc.warn('itemNode属性值不能为null');
            return;
        }

        let _width: number = this.itemNode.width;
        let _height: number = this.itemNode.height;
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.VERTICAL) {
            let t_boundary: number = this.m_View.y + this.m_View.height / 2 + _height;
            let b_boundary: number = this.m_View.y - this.m_View.height / 2 - _height;
            return [t_boundary, b_boundary];
        }
        else if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.HPRIZONTAL) {
            let l_boundary: number = this.m_View.x - this.m_View.width / 2 - _width;
            let r_boundary: number = this.m_View.x + this.m_View.width / 2 + _width;
            return [r_boundary, l_boundary];
        }
    }
    /**
     * 根据方向确定itemNode的位置
     * @param index 
     * @returns 
     */
    private _getPosFromDirction(index: number): cc.Vec3 {
        let temPos: cc.Vec3 = cc.Vec3.ZERO;
        let _width: number = this.itemNode.width;
        let _height: number = this.itemNode.height;
        switch (this.m_ContentDirection) {
            case CONTENT_DIRECTION_VERTICAL.TOP_TO_BOTTON:
                temPos = cc.v3(0, 0 - _height / 2 - (_height + this.spacing) * index, 0);
                break;
            case CONTENT_DIRECTION_VERTICAL.BOTTON_TO_TOP:
                temPos = cc.v3(0, 0 + _height / 2 + (_height + this.spacing) * index, 0);
                break;
            case CONTENT_DIRECTION_HORIZONTAL.LEFT_TO_RIGHT:
                temPos = cc.v3(0 + _width / 2 + (_width + this.spacing) * index, 0, 0);
                break;
            case CONTENT_DIRECTION_HORIZONTAL.RIGHT_TO_LEFT:
                temPos = cc.v3(0 - _width / 2 - (_width + this.spacing) * index, 0, 0);
                break;
        }

        return temPos;
    }
    /**
     * 设置content的尺寸
     * @param maxCount 
     */
    private _setContentSize(maxCount: number): void {
        let _width: number = this.itemNode.width;
        let _height: number = this.itemNode.height;
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.VERTICAL) {
            this.m_Content.setContentSize(cc.size(0, (_height + this.spacing) * maxCount - this.spacing));
        }
        else if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.HPRIZONTAL) {
            this.m_Content.setContentSize(cc.size((_width + this.spacing) * maxCount - this.spacing, 0));
        }
    }

    /**
     * 手动滑动刷新数据函数
     * 1竖向排列-上下滑动
     * 2横向排列-左右滑动
     * @param x_y 节点x，y属性
     * @param w_h 节点width，height属性
     */

    private lastTempDir: boolean = false;
    private _isHandSwitchShow(x_y: string, w_h: string) {
        let newPos: number = 0;
        let itemInfo: ItemInfo = null;
        let tempPos: cc.Vec3 = cc.Vec3.ZERO;
        let tempDir: boolean = this.m_Content[x_y] > this.m_LastContentPos[x_y];
        if (this.m_Content[x_y] == this.m_LastContentPos[x_y]) {
            tempDir = this.lastTempDir;
        }

        for (let i = 0; i < this.m_ItemInfos.length; i++) {
            itemInfo = this.m_ItemInfos[i];
            tempPos = this._getPositionInView(itemInfo.itemNode);
            if (tempDir) { //上滑和右滑
                newPos = itemInfo.itemNode[x_y] - this.m_OffsetHW;
                if (tempPos[x_y] > this.m_Boundary1 && newPos > 0 - this.m_Content[w_h] * (this.m_FlagDir == 1 ? 1 : 0)) {
                    itemInfo.itemNode[x_y] = newPos;
                    let index: number = itemInfo.id + this.m_ItemInfos.length * this.m_FlagDir;
                    itemInfo.id = index;
                    itemInfo.itemNode.name = nameStr + index;
                    this.m_Delegate.refreshInterface(index, index);
                    //break;
                }
            }
            else {  //下滑和左滑
                newPos = itemInfo.itemNode[x_y] + this.m_OffsetHW;
                if (tempPos[x_y] < this.m_Boundary2 && newPos < 0 - this.m_Content[w_h] * (this.m_FlagDir == -1 ? -1 : 0)) {
                    itemInfo.itemNode[x_y] = newPos;
                    let index: number = itemInfo.id - this.m_ItemInfos.length * this.m_FlagDir;
                    itemInfo.id = index;
                    itemInfo.itemNode.name = nameStr + index;
                    this.m_Delegate.refreshInterface(index, index);
                    //break;
                }
            }
        }
        this.lastTempDir = tempDir;
        this.m_LastContentPos = this.m_Content.position;
    }
    //+++++++++++++++++++++++++++++++++++++++++
    //+++++++++++++++++++++++++++++++++++++++++





    //+++++++++++++++++++++++++++++++++++++++++slider
    //+++++++++++++++++++++++++++++++++++++++++slider
    /*
     * 初始化slider
     */
    _initSlider(): void {
        if (!this.slider) { return; }
        this.slider.node.active = true;
        this.slider.progress = this._initSliderProgess();
        //定义handler内置事件
        let handler: cc.Node = cc.find('Handle', this.slider.node);
        handler.on(cc.Node.EventType.TOUCH_START, this._touchSliderBegin, this)
        handler.on(cc.Node.EventType.TOUCH_END, this._touchSliderEnd, this);
        handler.on(cc.Node.EventType.TOUCH_CANCEL, this._touchSliderEnd, this);
        //添加拖动事件
        let sliderEventHandler = new cc.Component.EventHandler();
        sliderEventHandler.target = this.node;
        sliderEventHandler.component = 'LoopScroll';
        sliderEventHandler.handler = 'changeContentFromPrgess';
        sliderEventHandler.customEventData = '';
        this.slider.slideEvents.push(sliderEventHandler);
        //记录初始位置
        this.m_CountInitPiont = this.m_Content.position;
    }
    /**
     * 点击的事件
     */
    private _touchSliderBegin(event: cc.Event): void {
        event.stopPropagation();
        this.m_InTouchSlider = true;
        this.m_ScrollView.stopAutoScroll();
    }
    private _touchSliderEnd(event: cc.Event) {
        event.stopPropagation();
        this.m_InTouchSlider = false;
    }
    /**
     * 初始设置progress
     * @returns 
     */
    private _initSliderProgess(): number {
        if (!this.slider) { return; }
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.VERTICAL) {
            this.slider.direction = cc.Slider.Direction.Vertical;
        }
        else if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.HPRIZONTAL) {
            this.slider.direction = cc.Slider.Direction.Horizontal;
        }

        let progess: number = 0;
        switch (this.m_ContentDirection) {
            case CONTENT_DIRECTION_VERTICAL.TOP_TO_BOTTON:
            case CONTENT_DIRECTION_HORIZONTAL.RIGHT_TO_LEFT:
                progess = 1;
                break;
            case CONTENT_DIRECTION_VERTICAL.BOTTON_TO_TOP:
            case CONTENT_DIRECTION_HORIZONTAL.LEFT_TO_RIGHT:
                progess = 0;
                break;
        }

        return progess;
    }
    /**
     * 更具方向获取slider的差值长度
     * @returns 
     */
    private _getSliderDistance(): number {
        if (!this.slider) { return; }
        let distance: number = 0;
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.VERTICAL) {
            distance = this.m_Content.height - this.m_View.height;
        }
        else if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.HPRIZONTAL) {
            distance = this.m_Content.width - this.m_View.width;
        }
        return distance;
    }

    private _setSliderProgess(value: number): void {
        if (!this.slider) { return; }
        let tempValue: number = 0;
        switch (this.m_ContentDirection) {
            case CONTENT_DIRECTION_VERTICAL.TOP_TO_BOTTON:
            case CONTENT_DIRECTION_HORIZONTAL.RIGHT_TO_LEFT:
                tempValue = 1 - cc.misc.clampf(value, 0, 1);
                break;
            case CONTENT_DIRECTION_VERTICAL.BOTTON_TO_TOP:
            case CONTENT_DIRECTION_HORIZONTAL.LEFT_TO_RIGHT:
                tempValue = cc.misc.clampf(value, 0, -1);
                break;
        }

        this.slider.progress = Math.abs(tempValue);
    }

    private changeContentFromPrgess(slider: cc.Slider, customEventData: string) {
        if (!this.slider) { return; }
        if (!this.itemNode) { return; }
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.NONE) { return; }

        slider.progress = cc.misc.clampf(slider.progress, 0, 1);
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.VERTICAL) {
            switch (this.m_ContentDirection) {
                case CONTENT_DIRECTION_VERTICAL.TOP_TO_BOTTON:
                    this.m_Content.y = this.m_CountInitPiont.y + this.m_SliderLength * (1 - slider.progress);
                    break;
                case CONTENT_DIRECTION_VERTICAL.BOTTON_TO_TOP:
                    this.m_Content.y = this.m_CountInitPiont.y - this.m_SliderLength * slider.progress;
                    break;
            }
        }
        else if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.HPRIZONTAL) {
            switch (this.m_ContentDirection) {
                case CONTENT_DIRECTION_HORIZONTAL.LEFT_TO_RIGHT:
                    this.m_Content.x = this.m_CountInitPiont.x - this.m_SliderLength * slider.progress;
                    break;
                case CONTENT_DIRECTION_HORIZONTAL.RIGHT_TO_LEFT:
                    this.m_Content.x = this.m_CountInitPiont.x + this.m_SliderLength * (1 - slider.progress);
                    break;
            }
        }
    }
    //+++++++++++++++++++++++++++++++++++++++++
    //+++++++++++++++++++++++++++++++++++++++++




    //+++++++++++++++++++++++++++++++++++++++++自动模式
    //+++++++++++++++++++++++++++++++++++++++++自动模式
    /**
     * 主要用于判断数据个数和可展示个数的对比情况，决定是否进入移动状态
     */
    private _getIsCanMoveState(maxCount: number): boolean {
        return maxCount >= this.m_ShowCount - offsetCount;
    }
    /**
     * 获取自动模式下选择的方向
     * @returns 
     */
    private _getDirectionFromAuto(): AUTO_DIRECTION_VERTICAL | AUTO_DIRECTION_HORIZONTAL {
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.VERTICAL) {
            return this.autoDirectionVertical;
        }
        else if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.HPRIZONTAL) {
            return this.autoDirectionHorizontal;
        }
    }
    /** 
     * 从上到下-从右到左的排列方式
     * 2中排列情况分别对应2中移动方向
     */
    private _isAutoSwitchShow1(dt: number, x_y: string) {
        let newPos: number = 0;
        let itemNode: cc.Node = null;
        let tempPos: cc.Vec3 = cc.Vec3.ZERO;
        if (this.m_AutoDirection == AUTO_DIRECTION_VERTICAL.TO_TOP || this.m_AutoDirection == AUTO_DIRECTION_HORIZONTAL.TO_RIGHT) {
            for (let i = 0; i < this.m_ItemInfos.length; i++) {
                itemNode = this.m_ItemInfos[i].itemNode;
                itemNode[x_y] += this.autoSpeed * dt;
                newPos = itemNode[x_y] - this.m_OffsetHW;
                tempPos = this._getPositionInView(itemNode);
                if (tempPos[x_y] >= this.m_Boundary1) {
                    itemNode[x_y] = newPos;
                    let index: number = this.m_LoopNodeCount++;
                    itemNode.name = nameStr + index % this.m_SumNodeCount;
                    this.m_Delegate.refreshInterface(index, index);
                }
                if (itemNode.active == false) {
                    itemNode.active = true;
                    let index: number = i % this.m_SumNodeCount;
                    itemNode.name = nameStr + index;
                    this.m_Delegate.refreshInterface(i, i);
                }
            }
        }
        else if (this.m_AutoDirection == AUTO_DIRECTION_VERTICAL.TO_BOTTON || this.m_AutoDirection == AUTO_DIRECTION_HORIZONTAL.TO_LEFT) {
            for (let i = this.m_ItemInfos.length - 1; i >= 0; i--) {
                itemNode = this.m_ItemInfos[i].itemNode;
                itemNode[x_y] -= this.autoSpeed * dt;
                newPos = itemNode[x_y] + this.m_OffsetHW;
                tempPos = this._getPositionInView(itemNode);
                if (tempPos[x_y] <= this.m_Boundary2) {
                    itemNode.active = true;
                    itemNode[x_y] = newPos;

                    this.m_LoopDataCount--;
                    this.m_LoopNodeCount--;
                    if (this.m_LoopNodeCount < 0) {
                        this.m_LoopNodeCount = this.m_SumNodeCount - 1;
                    }
                    if (this.m_LoopDataCount < 0) {
                        this.m_LoopDataCount = this.m_MaxShowCount - 1;
                    }
                    let index: number = this.m_LoopNodeCount;
                    itemNode.name = nameStr + index;
                    this.m_Delegate.refreshInterface(this.m_LoopNodeCount, this.m_LoopDataCount);
                }
            }
        }
    }
    /** 
     * 从下到上-从左到右的排列方式
     * 2中排列情况分别对应2中移动方向
     */
    private _isAutoSwitchShow2(dt: number, x_y: string) {
        let newPos: number = 0;
        let itemNode: cc.Node = null;
        let tempPos: cc.Vec3 = cc.Vec3.ZERO;
        if (this.m_AutoDirection == AUTO_DIRECTION_VERTICAL.TO_TOP || this.m_AutoDirection == AUTO_DIRECTION_HORIZONTAL.TO_RIGHT) {
            for (let i = this.m_ItemInfos.length - 1; i >= 0; i--) {
                itemNode = this.m_ItemInfos[i].itemNode;
                itemNode[x_y] += this.autoSpeed * dt;
                newPos = itemNode[x_y] - this.m_OffsetHW;
                tempPos = this._getPositionInView(itemNode);
                if (tempPos[x_y] >= this.m_Boundary1) {
                    itemNode.active = true;
                    itemNode[x_y] = newPos;

                    this.m_LoopDataCount--;
                    this.m_LoopNodeCount--;
                    if (this.m_LoopNodeCount < 0) {
                        this.m_LoopNodeCount = this.m_SumNodeCount - 1;
                    }
                    if (this.m_LoopDataCount < 0) {
                        this.m_LoopDataCount = this.m_MaxShowCount - 1;
                    }
                    let index: number = this.m_LoopNodeCount;
                    itemNode.name = nameStr + index;
                    this.m_Delegate.refreshInterface(this.m_LoopNodeCount, this.m_LoopDataCount);
                }
            }
        }
        else if (this.m_AutoDirection == AUTO_DIRECTION_VERTICAL.TO_BOTTON || this.m_AutoDirection == AUTO_DIRECTION_HORIZONTAL.TO_LEFT) {
            for (let i = 0; i < this.m_ItemInfos.length; i++) {
                itemNode = this.m_ItemInfos[i].itemNode;
                itemNode[x_y] -= this.autoSpeed * dt;
                newPos = itemNode[x_y] + this.m_OffsetHW;
                tempPos = this._getPositionInView(itemNode);
                if (tempPos[x_y] <= this.m_Boundary2) {
                    itemNode[x_y] = newPos;

                    let index: number = this.m_LoopNodeCount++;
                    itemNode.name = nameStr + index % this.m_SumNodeCount;
                    this.m_Delegate.refreshInterface(index, index);
                }
                if (itemNode.active == false) {
                    itemNode.active = true;
                    let index: number = i % this.m_SumNodeCount;
                    itemNode.name = nameStr + index;
                    this.m_Delegate.refreshInterface(i, i);
                }
            }
        }
    }
    //++++++++++++++++++++++++++++++++++++++
    //++++++++++++++++++++++++++++++++++++++
    /**
     * 坐标转换
     * @param itemNode 
     * @returns 
    */
    private _getPositionInView(itemNode: cc.Node): cc.Vec3 {
        let worldPos = itemNode.parent.convertToWorldSpaceAR(itemNode.position);
        let viewPos = this.m_View.convertToNodeSpaceAR(worldPos);
        return viewPos;
    }

    /**
     * 设置调用者的实例对象
     * @param delegate this
     */
    public setDelegate(delegate: BaseUI): void {
        if (delegate) {
            this.m_Delegate = delegate;
        }
        else {
            cc.warn('delegate参数为null');
        }
    };
    /**
     * 初始化content数据
     * @param maxCount  数据个数
     */
    public initContentData(maxCount: number): void {
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.NONE) { return; }
        if (!this.m_Delegate) { return; }
        if (!this.itemNode) { return; }

        let count: number = Math.min(maxCount, this.m_ShowCount);
        for (let i = 0; i < count; i++) {
            let itemInfo: ItemInfo = this.m_ItemInfos[i];
            itemInfo.itemNode.name = nameStr + i;
            itemInfo.id = i;
            itemInfo.itemNode.setAnchorPoint(cc.v2(0.5, 0.5));
            itemInfo.itemNode.active = i < this.m_ShowCount;
            this.m_Delegate.refreshInterface(i, i);
        }

        if (this.isOpenAuto) {
            //自动模式下的准备
            this.m_LoopDataCount = this.m_MaxShowCount = maxCount;
            this.m_LoopNodeCount = this.m_SumNodeCount = this.m_ItemInfos.length;
            this.m_isMoveState = this._getIsCanMoveState(maxCount);
        }
        else {
            //手动模式需要设置content的尺寸
            this._setContentSize(maxCount);
            this.m_SliderLength = this._getSliderDistance();
        }
    }


    update(dt: number) {
        if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.NONE) { return; }
        if (!this.m_Delegate) { return; }
        if (!this.itemNode) { return; }

        if (!this.isOpenAuto) {
            //手动模式
            // if (this.m_Content.position.equals(this.m_LastContentPos)) { return; }
            if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.VERTICAL) {
                this._isHandSwitchShow('y', 'height');
                if (!this.m_InTouchSlider) {
                    let tempValue: number = (this.m_Content.y - this.m_CountInitPiont.y) / this.m_SliderLength;
                    this._setSliderProgess(tempValue);
                }
            }
            else if (this.m_ScrollViewDirection == SCROLLVIEW_DIRECTION.HPRIZONTAL) {
                this._isHandSwitchShow('x', 'width');
                if (!this.m_InTouchSlider) {
                    let tempValue: number = (this.m_Content.x - this.m_CountInitPiont.x) / this.m_SliderLength;
                    this._setSliderProgess(tempValue);
                }
            }
        }
        else {
            //自动模式- 4中排列方式每种都2中移动方向
            if (this.m_isMoveState) {
                switch (this.m_ContentDirection) {
                    case CONTENT_DIRECTION_VERTICAL.TOP_TO_BOTTON:
                        this._isAutoSwitchShow1(dt, 'y');
                        break;
                    case CONTENT_DIRECTION_VERTICAL.BOTTON_TO_TOP:
                        this._isAutoSwitchShow2(dt, 'y');
                        break;
                    case CONTENT_DIRECTION_HORIZONTAL.LEFT_TO_RIGHT:
                        this._isAutoSwitchShow2(dt, 'x');
                        break;
                    case CONTENT_DIRECTION_HORIZONTAL.RIGHT_TO_LEFT:
                        this._isAutoSwitchShow1(dt, 'x');
                        break;
                }
            }
        }
    }
}
